
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

# 初始化配置
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

# 数据加载
nodes = pd.read_csv("part2.csv")  # 原
edges = pd.read_csv("part1.csv")  # 原

# 构建有向图
G = nx.DiGraph()
for _, row in nodes.iterrows():
    G.add_node(row['id'], name=row['name'])
for _, row in edges.iterrows():
    G.add_edge(row['src'], row['dst'], relation=row['relationship'])

# 可视化设置
plt.figure(figsize=(16, 12))
pos = nx.spring_layout(G, k=0.7, seed=42)

# 绘制节点（蓝色渐变）
nx.draw_networkx_nodes(
    G, pos,
    node_size=2800,
    node_color='#4B9CD3',
    edgecolors='#1F4E79',
    linewidths=2
)

# 绘制带箭头的边（灰色曲线）
nx.draw_networkx_edges(
    G, pos,
    arrowsize=20,
    arrowstyle='->',
    edge_color='#7F7F7F',
    width=1.2,
    connectionstyle='arc3,rad=0.1'
)

# 添加标签
nx.draw_networkx_labels(
    G, pos,
    labels={n:d['name'] for n,d in G.nodes(data=True)},
    font_size=11,
    font_weight='bold'
)

# 添加关系标签
nx.draw_networkx_edge_labels(
    G, pos,
    edge_labels={(u,v):d['relation'] for u,v,d in G.edges(data=True)},
    font_size=9,
    bbox=dict(alpha=0.8)
)

plt.title("《人物关系网络图》", fontsize=16, pad=20)
plt.axis('off')
plt.tight_layout()
plt.savefig('人物关系网络图.png', dpi=300)
plt.show()
